package com.cans.web.file;

import com.cans.config.CansFileProperties;
import com.cans.dto.ResDto;
import com.cans.model.file.FileDetail;
import com.cans.model.pms.SysUser;
import com.cans.service.pms.api.IFileDetailService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * @author cans
 * @date 2018/6/4
 * @description 文件操作web层
 */
@Controller
@RequestMapping("/file")
public class FileDetailController {

    @Resource
    private IFileDetailService fileDetailService;
    @Resource
    private CansFileProperties cansFileProperties;

    /**
     * 文件上传
     * @return
     */
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public ResDto upload(@RequestParam("file") MultipartFile file) throws IOException {
        if(file.isEmpty()){
            return ResDto.fait("文件为空");
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);

        String path = cansFileProperties.getBasePath() ;
        File dest = new File(path + "/" + fileName);
        //判断文件父目录是否存在
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }
        //保存文件
        file.transferTo(dest);

        FileDetail fileDetail = new FileDetail();
        SysUser user = (SysUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        // 文件名
        fileDetail.setFileName(fileName);
        // 文件类型
        String type = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        fileDetail.setFileType(type);
        // 文件路劲
        fileDetail.setUrl(path + "/" + fileName);
        // 上传人员ID
        fileDetail.setUploadUserId(user.getId());
        // 保存
        FileDetail save = fileDetailService.save(fileDetail);

        return ResDto.success(save);

    }
}
